#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: twl
@date: 2022/4/10 16:47
@description:
"""

import sys

from flask import Flask
from base.constant.nacos_constants import *
from base.entity.base_entity import db
from base.util.nacos_util import NacosUtil
from base.util.ip_util import IpUtil
from common.boot_args import config_name, port
from common.logger import LoggerHandler
from config import profiles
from yml_init_load import YmlInitLoad

logging = LoggerHandler(__name__)


def create_app():
    from v1.health_api import health
    from v1.sleep_time_api import sleepTime
    from v1.wakeup_time_api import wakeupTime
    from log.bluetooth_ui import bluetooth
    new_app = Flask(__name__)
    logging.info('当前配置：' + config_name)
    new_app.config.from_object(profiles.app_config[config_name])
    logging.info(new_app.config['SQLALCHEMY_DATABASE_URI'])
    new_app.register_blueprint(health, url_prefix='/')
    new_app.register_blueprint(sleepTime, url_prefix='/sleepTime')
    new_app.register_blueprint(wakeupTime, url_prefix='/wakeUpTime')
    new_app.register_blueprint(bluetooth, url_prefix='/bluetooth')
    # #数据库配置
    db.init_app(new_app)
    return new_app


def init_nacos(new_app, final_port):
    from common import global_val as gol
    gol.init()
    NACOS_SERVER_ADDRESSES = new_app.config['NACOS_SERVER_ADDRESSES']
    NACOS_GROUP = new_app.config['NACOS_GROUP']
    NACOS_NAMESPACE = new_app.config['NACOS_NAMESPACE']
    SERVICE_REGISTER_GROUP = new_app.config['SERVICE_REGISTER_GROUP']
    server_id = IpUtil.get_host_ip()
    gol.set_value(SERVER_ID_KEY, server_id)
    gol.set_value(SERVER_PORT_KEY, final_port)
    # 获取任务开启状态
    data = NacosUtil.get_content(NACOS_SERVER_ADDRESSES, NACOS_NAMESPACE, NACOS_GROUP, PROACTIVE_SERVICE_YML)
    YmlInitLoad.set_value_for_proactive_service(data, gol)
    # 设置监听
    NacosUtil.add_config_watcher(NACOS_SERVER_ADDRESSES, NACOS_NAMESPACE, NACOS_GROUP, PROACTIVE_SERVICE_YML,
                                 callback_for_nacos)


# 添加服务实例
# NacosUtil.add_naming_instance(NACOS_SERVER_ADDRESSES, NACOS_NAMESPACE, SERVICE_REGISTER_GROUP, SERVER_NAME,
#                               server_id, final_port,
#                               CLUSTER_NAME)


def callback_for_nacos(content):
    logging.info('callback_for_nacos: ' + str(content))
    from common import global_val as gol
    NACOS_SERVER_ADDRESSES = app.config['NACOS_SERVER_ADDRESSES']
    NACOS_GROUP = app.config['NACOS_GROUP']
    NACOS_NAMESPACE = app.config['NACOS_NAMESPACE']
    data = NacosUtil.get_content(NACOS_SERVER_ADDRESSES, NACOS_NAMESPACE, NACOS_GROUP, PROACTIVE_SERVICE_YML)
    YmlInitLoad.set_value_for_proactive_service(data, gol)


app = create_app()

if __name__ == '__main__':
    final_port = port if port is not None else 8668
    init_nacos(app, final_port)
    app.run(host="0.0.0.0", port=final_port, use_reloader=False)
